import json
import os
import random
import time
import datetime

from django.conf import settings
from django.http import JsonResponse
from rest_framework import viewsets, status, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.permissions import IsAuthenticated

# from .models import FileHistory


class UploadViewSet(GenericViewSet):
    # permission_classes = [IsAuthenticated]

    @action(methods=['post'], detail=False, url_path='upload')
    def upload_file(self, request, pk=None):
        """ 上传文件(只能上传音视频和图片) """
        file = request.data.get('file', None)   # 上传的文件
        dir_name = request.data.get('dir_name', '')     # 需要保存在哪里
        # upload_key = request.data.get('upload_key', '')     # 表单的key
        if not all([file, dir_name]):
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        if file.content_type.split('/')[0] not in ['video', 'audio', 'image']:
            return Response({'message': '上传文件出错：上传了不允许的文件类型。'}, status=status.HTTP_400_BAD_REQUEST)

        file_name = file.name
        dir_path = f"{settings.MEDIA_ROOT}/survey_system/{dir_name}"
        if not os.path.exists(dir_path):  # 没有该目录就创建
            os.makedirs(dir_path)
        # 给文件重新命名，避免重复
        now_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        new_file_name = f"{now_str}-{file_name}"
        file_path = os.path.join(dir_path, new_file_name)
        # 写入文件
        with open(file_path, 'ab') as fp:
            # 如果上传的文件非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in file.chunks():
                fp.write(chunk)
        file_path = f'survey_system/{dir_name}/{new_file_name}'

        # 写入后创建一条记录
        # if upload_key:
        #     FileHistory.objects.create(upload_key=upload_key, path=file_path)

        res_data = {
            'url': file_path,
            'content_type': file.content_type,
            "full_url": f"{settings.FILE_URL}{file_path}",
            'name': new_file_name,
        }

        return Response(res_data)
